//
//  StatusPictureView.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/12.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit
import SDWebImage


/// 普通微博标识
let StatusPictureViewCellNormalID = "StatusPictureViewCellNormalID"

//MARK: - 配图视图
class StatusPictureView: UICollectionView {
    
    ///单条微博 视图模型
    var viewModel: StatusViewModel? {
        didSet {
            //自动计算大小
            sizeToFit()
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calculateViewSize()
    }

    /// 构造方法 初始化 collectionView
    ///
    /// - returns: pictureView
    init() {
        /// 流水布局
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = PictureViewItemMargin - 1
        layout.minimumLineSpacing = PictureViewItemMargin
//        layout.scrollDirection = .Horizontal
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //数据源代理
        dataSource = self
        delegate = self
        scrollEnabled = false
        //注册可重用标识
        registerClass(StatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewCellNormalID)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 配图图片间距
    private let PictureViewItemMargin: CGFloat = 8
    
}

// MARK: - UICollectionView代理方法
extension StatusPictureView: UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        print("点击了 \(indexPath.item) URL \(viewModel?.thumbnailURLs)")
        
        let userinfo = [WBUserInfoKeyStatusSelectedPhotoIndex: indexPath,
                         WBUserInfoKeyStatusSelectedPhotoURLs: viewModel!.thumbnailURLs!]
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBNotificationStatusSelectedPhoto,
            object: self,
            userInfo: userinfo)
    }
}

// MARK: - StatusPictureView 数据源方法
extension StatusPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(StatusPictureViewCellNormalID, forIndexPath: indexPath) as! StatusPictureViewCell
        
        cell.imageUrl = viewModel?.thumbnailURLs![indexPath.row]
        
        return cell
    }
}

// MARK: - 实现代理方法
extension StatusPictureView: PhotoBrowserPresentDelegate {
    /// 返回要展现动画的图片
    ///
    /// - parameter indexPath: 图片索引
    ///
    /// - returns: 图片
    func imageViewForPresentAnimator(indexPath: NSIndexPath) -> UIImageView {
        
        let animateImageView = UIImageView()
        animateImageView.contentMode = UIViewContentMode.ScaleAspectFill
        animateImageView.clipsToBounds = true
        //从磁盘缓存去缩略图
        let key = viewModel?.thumbnailURLs![indexPath.item].absoluteString
        animateImageView.image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
        return animateImageView
    }
    
    /// 图片起始位置
    ///
    /// - parameter indexPath: 图片索引
    ///
    /// - returns: 图片位置
    func fromRectForPresentAnimator(indexPath: NSIndexPath) -> CGRect {
        //取得当前 cell 的坐标系转换为 keywindow 的坐标系
        let cell = cellForItemAtIndexPath(indexPath)!
        let rect = self.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)

        return rect
    }
    
    /// 图片最终位置
    ///
    /// - parameter IndexPath: 索引
    ///
    /// - returns: 图片位置
    func toRectForPresentAnimator(IndexPath: NSIndexPath) -> CGRect {
        //取得磁盘缓存缩略图
        let key = viewModel!.thumbnailURLs![IndexPath.item].absoluteString
        guard let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) else {
            return CGRectZero
        }
        //等比例换算大小
        let w = UIScreen.mainScreen().bounds.width
        let h = image.size.height * w / image.size.width
        var y: CGFloat = 0
        
        let screenHeight = UIScreen.mainScreen().bounds.height
        if h < screenHeight {
            y = (screenHeight - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)

    }
}

// MARK: - 计算视图大小
extension StatusPictureView {
    
    private func calculateViewSize() -> CGSize {
        /// 列数
        let column: CGFloat = 3
        /// View 宽度
        let viewWith = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
        /// 图片宽度
        let picWith = (viewWith - 2 * PictureViewItemMargin) / column
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSizeMake(picWith, picWith)
        
         /// 图片数量
        let picCount = viewModel?.thumbnailURLs?.count ?? 0
        
        if picCount == 0 {
            layout.itemSize = CGSize(width: 1, height: 1)
            return CGSizeZero
        }
        
        if picCount == 1 {

            var size = CGSize()
            
            if let key = viewModel?.thumbnailURLs?.first?.absoluteString {

                if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key) {
                
                size = image.size
                }
            }

            // 过窄处理 - 针对长图
            size.width = size.width < 40 ? 40 : size.width
            // 过宽的图片
            if size.width > 300 {
                let w: CGFloat = 300
                let h = size.height * w / size.width
                
                size = CGSize(width: w, height: h)
            }
            
            layout.itemSize = size
            
            return size
        }
        
        if picCount == 4 {
            let w = picWith * 2 + PictureViewItemMargin
            return CGSizeMake(w, w)
        }
        
        // 4> 其他图片 按照九宫格来显示
        /// View行数
        let row = CGFloat((picCount - 1) / Int(column) + 1)
        /// View高度
        let h = row * picWith + (row - 1) * PictureViewItemMargin
        /// View宽度
        let w = column * picWith + (column - 1) * PictureViewItemMargin
        
        return CGSizeMake(w, h)
    }
}

//MARK: - 配图 Cell
class StatusPictureViewCell: UICollectionViewCell {
    
    /// 配图地址
    var imageUrl: NSURL? {
        didSet {
            //给子控件赋值
            iconView.sd_setImageWithURL(imageUrl,
                placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,
                SDWebImageOptions.RefreshCached])
            
            let urlString = (imageUrl?.absoluteString ?? "" as NSString)
            let hidden = urlString.pathExtension.lowercaseString != "gif"
            GIFView.hidden = hidden
        }
        
    }
    
    // MARK: - 懒加载子控件
    /// GIF 标识
    private lazy var GIFView: UIImageView = UIImageView(imageName: "timeline_image_gif")
    /// 图片视图
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        //配图填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
    
    /// 初始化 Cell 的构造方法
    ///
    /// - returns:  collectionViewCell
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置 UI
    private func setupUI() {
        
    /// 添加子控件
        contentView.addSubview(iconView)
        iconView.addSubview(GIFView)
    /// 布局子控件
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        GIFView.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(iconView)
            make.bottom.equalTo(iconView)
        }
    }
    
}





